import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-22
 * Time: 14:41
 */
public class UdpEchoClient {
    private String Ip;
    private int port;
    private DatagramSocket socket = null;
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.Ip = serverIp;
        this.port = serverPort;
        socket = new DatagramSocket();  //操作系统随机分配端口给客户端
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的内容");
            String requset = scanner.next();
            //构造请求数据包
            DatagramPacket requestPacket = new DatagramPacket(requset.getBytes()
                    , 0, requset.getBytes().length,
                    InetAddress.getByName(Ip), port);
            //发送请求数据包
            socket.send(requestPacket);
            //接受服务器的响应数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //转换成String方便打印结果
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
